﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Web;
using System.Web.Security;
using System.Security.Claims;
using IdentityModel.Client;
using System.Threading.Tasks;
using System.Linq;
//using Microsoft.IdentityModel.Claims;
using System.Threading;
using System.Xml.Linq;

namespace WebForms.Account
{
    public partial class Callback : System.Web.UI.Page
    {
        public const string SessionID = "SessionID";
        public const string SessionUserName = "SessionUserName";
        public const string SSOPassport = "SSOPassport";
        public const string SSOAppID = "SSOAppID";
        protected void Page_Load(object sender, EventArgs e)
        {
            string code = HttpContext.Current.Request.Params["code"];
            string state = HttpContext.Current.Request.Params["state"];
            string tokenEndpoint = "https://localhost:5001/connect/token";
            string clientId = "webforms";
            string clientSecret = "secret";
            string redirectUri = "https://localhost:44379/account/callback";

            // 从会话中获取之前存储的code_verifier
            var codeVerifier = HttpContext.Current.Session["CodeVerifier"];
            if (codeVerifier == null)
            {
                Response.Redirect("/");
            }
            var values = new Dictionary<string, string>
                {
                    {"grant_type", "authorization_code"},
                    {"client_id", clientId},
                    {"client_secret", clientSecret},
                    {"code", code},
                    {"redirect_uri", redirectUri},
                    {"scope", "openid profile api1"},
                    {"code_verifier", codeVerifier.ToString()} // 包含code_verifier

                };

            using (var client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(values);
                var response = client.PostAsync(tokenEndpoint, content).Result;
                var responseContent = response.Content.ReadAsStringAsync().Result;

                // 解析令牌响应
                dynamic jsonResponse = JsonConvert.DeserializeObject(responseContent);
                string accessToken = jsonResponse.access_token;
                string refreshToken = jsonResponse.refresh_token;
                string idToken = jsonResponse.id_token;
                var principal = GetPrincipalFromToken(idToken);
                SignWebForms(principal);


                // 保存令牌信息
                HttpContext.Current.Session.Add("AccessToken", accessToken);
                HttpContext.Current.Session.Add("RefreshToken", refreshToken);
                HttpContext.Current.Session.Add("IdToken", idToken);
                Response.Redirect("/");
                // 重定向到主页或其他页面
                //return redirectUri("Index", "Home");
            }
        }

        private static void SignWebForms(ClaimsPrincipal principal)
        {
            // 设置当前线程的身份
            Thread.CurrentPrincipal = principal;
            HttpContext.Current.User = principal;

            // 创建Forms Authentication ticket
            var ticket = new FormsAuthenticationTicket(
                1, // 版本
                principal.Identity.Name, // 用户名
                DateTime.Now, // 创建时间
                DateTime.Now.AddMinutes(30), // 过期时间
                false, // 是否记住我
                principal.Identity.AuthenticationType, // 认证类型
                ""); // Cookie路径

            // 对ticket进行加密
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);

            // 设置cookie
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            //authCookie.Name = "idsrv2";
            authCookie.HttpOnly = true; // 设定cookie为httpOnly属性增加安全性
            HttpContext.Current.Response.Cookies.Add(authCookie);
            FormsAuthentication.RedirectFromLoginPage(principal.Identity.Name, false);
        }

        public ClaimsPrincipal GetPrincipalFromToken(string idToken)
        {
            var handler = new JwtSecurityTokenHandler();
            var jwtToken = handler.ReadJwtToken(idToken);
            var principal = new ClaimsPrincipal(new ClaimsIdentity(jwtToken.Claims, "jwt","name","role"));
            return principal;
        }

        public async Task<ClaimsPrincipal> GetUserInformationAsync(string accessToken)
        {
            using (var client = new HttpClient())
            {
                client.SetBearerToken(accessToken);
                var response = await client.GetAsync("https://youridentityserver.com/connect/userinfo");
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    // 假设返回的是JSON格式的数据
                    dynamic userInfo = JsonConvert.DeserializeObject(content);
                    // 创建一个ClaimsPrincipal对象
                    var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, userInfo.sub),
                // 添加其他claim...
            };
                    var identity = new ClaimsIdentity(claims, "userInfo");
                    return new ClaimsPrincipal(identity);
                }
                else
                {
                    throw new Exception("Failed to retrieve user info from IdentityServer.");
                }
            }
        }
    }
}